package com.hps.demo.aspect;

import com.alibaba.fastjson.JSON;
import com.hps.demo.util.IpUtil;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author heps
 * @since 2020/7/23 10:36
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

  @Pointcut("execution(* com.hps.demo.controller.*.*(..))")
  public void pointcut() {}

  @Around(value = "pointcut()")
  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Object object;
    long startTime = System.currentTimeMillis();
    HttpServletRequest request = ((ServletRequestAttributes) Objects
        .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    //类名
    String className = joinPoint.getTarget().getClass().getName();
    //请求方法
    String method =  joinPoint.getSignature().getName() + "()";
    //方法参数
    String methodParam = JSON.toJSONString(joinPoint.getArgs());

    StringBuilder sb = new StringBuilder(1000);
    sb.append("\n");
    sb.append("*********************************Request请求开始***************************************");
    sb.append("\n");
    sb.append("ClassName     :  ").append(className).append("\n");
    sb.append("RequestMethod :  ").append(method).append("\n");
    sb.append("RequestParams :  ").append(methodParam).append("\n");
    sb.append("RequestType   :  ").append(request.getMethod()).append("\n");
    sb.append("serverAddr    :  ").append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append("\n");
    sb.append("UserAgent     :  ").append(request.getHeader("User-Agent")).append("\n");
    sb.append("RequestUri    :  ").append(request.getRequestURI()).append("\n");
    sb.append("RemoteAddr    :  ").append(IpUtil.getIpAddr(request));
    log.info(sb.toString());

    object = joinPoint.proceed();

    //请求方法
    sb = new StringBuilder(1000);
    // 处理完请求，返回内容
    sb.append("\n");
    sb.append("Result        :  ").append(JSON.toJSONString(object)).append("\n");
    sb.append("Request time  :  ").append((System.currentTimeMillis() - startTime)).append("ms\n");
    sb.append("*********************************Request请求结束***************************************");
    log.info(sb.toString());

    return object;
  }
}
